package com.lijie.ljblog.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lijie.ljblog.common.BlogConstants;
import com.lijie.ljblog.model.Person;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Authorr 李杰
 * @Date：2022/11/2917:41
 **/
@Service
public class JwtUtil {

    @Value("${token.privateKey}")
    private String privateKey;

    /**
     * 加密token.
     */
    public String getToken(String userId, String userName,String userRole) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        String token = JWT
                .create()
                .withClaim(BlogConstants.TOEKN_ID,userId)
                .withClaim(BlogConstants.TOEKN_NAME, userName)
                .withClaim(BlogConstants.TOEKN_ROLE, userRole)
                .withClaim(BlogConstants.TOEKN_TIME, System.currentTimeMillis())
                .sign(Algorithm.HMAC256(privateKey));
        return token;
    }
    /**
     * 加密token.
     */
    public String getToken(Person person) {
        //这个是放到负载payLoad 里面,魔法值可以使用常量类进行封装.
        String token = JWT
                .create()
                .withClaim(BlogConstants.TOEKN_ID,person.getId())
                .withClaim(BlogConstants.TOEKN_NAME, person.getUserName())
                .withClaim(BlogConstants.TOEKN_ROLE, person.getType())
                .withClaim(BlogConstants.TOEKN_TIME, System.currentTimeMillis())
                .sign(Algorithm.HMAC256(privateKey));
        return token;
    }

    /**
     * 解析token.
     * (优化可以用常量固定魔法值+使用DTO在 mvc 之前传输数据，而不是 map,这里因为篇幅原因就不做了)
     * {
     * "userId": "3412435312",
     * "userRole": "ROLE_USER",
     * "timeStamp": "134143214"
     * }
     */
    public Person parseToken(String token) {
        Person person = new Person();
        DecodedJWT decodedjwt = JWT.require(Algorithm.HMAC256(privateKey))
                .build().verify(token);
        Claim userId = decodedjwt.getClaim(BlogConstants.TOEKN_ID);
        Claim userName = decodedjwt.getClaim(BlogConstants.TOEKN_NAME);
        Claim userRole = decodedjwt.getClaim(BlogConstants.TOEKN_ROLE);
        Claim timeStamp = decodedjwt.getClaim(BlogConstants.TOEKN_TIME);
        person.setId(userId.asInt());
        person.setUserName(userName.asString());
        person.setType(userRole.asString());
        return person;
    }

}
